package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.TopDish;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/presentation")
@Slf4j
public class PresentationDataController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @GetMapping
    public R<Object> getPresentationData(){
        log.info("进到这里来了");
        Map<String, BigDecimal> orderDetail= orderService.getMonthlyRevenues();
        return R.success(orderDetail);
    }
    @GetMapping("/top")
    public R<Object>getTop10DishByAmount(){
        QueryWrapper<OrderDetail> quantityWrapper = Wrappers.query();
        quantityWrapper.groupBy("name")
                .select("name as name, SUM(number) as totalQuantity")
                .orderByDesc("totalQuantity")
                .last("LIMIT 10");
        List<OrderDetail> top10DishesByQuantity = orderDetailMapper.selectList(quantityWrapper);

        QueryWrapper<OrderDetail> amountWrapper = Wrappers.query();
        amountWrapper.groupBy("name")
                .select("name as name, SUM(amount) as totalAmount")
                .orderByDesc("totalAmount")
                .last("LIMIT 10");
        List<OrderDetail> top10DishesByAmount = orderDetailMapper.selectList(amountWrapper);

        List<TopDish> combinedList = new ArrayList<>();

        // Merge the two lists into a single list
        for (OrderDetail quantityDish : top10DishesByQuantity) {
            for (OrderDetail amountDish : top10DishesByAmount) {
                if (quantityDish.getName().equals(amountDish.getName())) {
                    TopDish topDish = new TopDish();
                    topDish.setName(quantityDish.getName());
                    topDish.setTotalQuantity((int) quantityDish.getTotalQuantity());
                    topDish.setTotalAmount(amountDish.getTotalAmount());
                    combinedList.add(topDish);
                    break;
                }
            }
        }
        return R.success(combinedList);
    }

}
